import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:test/pages/notification/listener.dart';
import 'package:test/providers/user_token_provider.dart';
import 'package:test/apis/user.dart';
import 'package:test/pages/home/index.dart' deferred as homeIndex;
import 'package:test/pages/user/info.dart' deferred as userInfo;
import 'package:test/routes/default_page_route.dart';
import 'package:test/routes/scale_page_route.dart';
import 'package:test/routes/slide_page_route.dart';
import 'package:test/theme/ui_theme.dart';
import 'package:test/vendors/tdesign_flutter/lib/tdesign_flutter.dart';
import 'package:test/providers/theme_provider.dart';

class HomeIndexPage extends StatefulWidget {
  const HomeIndexPage({super.key});

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title = '首页';

  @override
  State<HomeIndexPage> createState() => _HomeIndexPageState();
}

class _HomeIndexPageState extends State<HomeIndexPage> {

  int _counter = 0;

  static const toastPlugin = MethodChannel('toast_plugin');

  void _incrementCounter() {
    setState(() {
      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below
      // so that the display can reflect the updated values. If we changed
      // _counter without calling setState(), then the build method would not be
      // called again, and so nothing would appear to happen.
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      appBar: AppBar(
        // TRY THIS: Try changing the color here to a specific color (to
        // Colors.amber, perhaps?) and trigger a hot reload to see the AppBar
        // change color while the other colors stay the same.
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Center(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: SingleChildScrollView(
          // Column is also a layout widget. It takes a list of children and
          // arranges them vertically. By default, it sizes itself to fit its
          // children horizontally, and tries to be as tall as its parent.
          //
          // Column has various properties to control how it sizes itself and
          // how it positions its children. Here we use mainAxisAlignment to
          // center the children vertically; the main axis here is the vertical
          // axis because Columns are vertical (the cross axis would be
          // horizontal).
          //
          // TRY THIS: Invoke "debug painting" (choose the "Toggle Debug Paint"
          // action in the IDE, or press "p" in the console), to see the
          // wireframe for each widget.
          child: Column(children: [
            Consumer(builder: (context, ref, _) {
              final userToken = ref.watch(userTokenProvider);
              return Text(userToken ?? 'Token is null');
            }),
            Text(Localizations.of(context, MaterialLocalizations)?.hello),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headlineMedium,
            ),
            Consumer(builder: (context, ref, _) {
              final userToken = ref.watch(userTokenProvider);
              return Text(userToken ?? 'Token is null');
            }),
            Consumer(builder: (context, ref, _) {
              return ElevatedButton(
                onPressed: () async {
                  try {
                    await UserApi.login();
                  } catch(e) {
                    print('请求失败');
                  }
                  ref.read(userTokenProvider.notifier).updateToken('newToken');
                },
                child: const Text('模拟登录'),
              );
            }),
            Consumer(builder: (context, ref, _) {
              return ElevatedButton(onPressed: () {
                ref.read(themeProvider.notifier).updateTheme('dark');
              }, child: const Text('昏暗主题'));
            }),
            Consumer(builder: (context, ref, _) {
              return ElevatedButton(onPressed: () {
                ref.read(themeProvider.notifier).updateTheme('light');
              }, child: const Text('明亮主题'));
            }),
            Container(
              width: 100,
              height: 60,
              decoration: context.createDecoration(),
              child: Center(
                child: const Text('UI主题: 卡片背景', style: TextStyle(color: Colors.grey),),
              ),
            ),
            ElevatedButton(onPressed: () async {
              // 异步加载页面资源
              await homeIndex.loadLibrary();
              Navigator.push(context, DefaultPageRoute(homeIndex.HomeIndexPage()));
            }, child: const Text('页面跳转1')),
            ElevatedButton(onPressed: () async {
              // 异步加载页面资源
              await homeIndex.loadLibrary();
              Navigator.push(context, ScalePageRoute(homeIndex.HomeIndexPage()));
            }, child: const Text('页面跳转2')),
            ElevatedButton(onPressed: () async {
              // 异步加载页面资源
              await homeIndex.loadLibrary();
              Navigator.push(context, SlidePageRoute(homeIndex.HomeIndexPage()));
            }, child: const Text('页面跳转3')),
            Image.asset('assets/images/icon.jpeg', width: 100, height: 100),
            ElevatedButton(onPressed: () async {
              // 异步加载页面资源
              await userInfo.loadLibrary();
              Navigator.push(context, SlidePageRoute(userInfo.UserInfoPage()));
            }, child: const Text('自定义组件')),
            ElevatedButton(onPressed: () async {
              final result = await toastPlugin.invokeMethod("toast", {'message': '调用成功'});
              print('原生接口返回结果：${result}');
            }, child: const Text('调用原生能力')),
            const TDButton(
              text: '填充按钮',
              icon: TDIcons.app,
              size: TDButtonSize.large,
              type: TDButtonType.fill,
              shape: TDButtonShape.rectangle,
              theme: TDButtonTheme.primary,
            ),
            NotificationListenerWidget(),
          ]),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.settings),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}